<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>控制台</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/component/pear/css/pear.css" />
    <link rel="stylesheet" href="/admin/css/other/console1.css" />
    <style>
        .header-th div.layui-table-header th div {
            text-align: center;
        }

        .divider-vl {
            display: inline-block;
            width: 1px;
            height: 1em;
            margin: 0 8px;
            vertical-align: middle;
            position: relative;
            background-color: #dcdfe6;
        }
    </style>
</head>

<body class="pear-container">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-row">
                <div class="layui-col-xs12"></div>
                <div class="layui-col-xs12">
                    <table id="plugin-table" lay-filter="plugin-table"></table>
                </div>
            </div>
        </div>
    </div>
    <script type="text/html" id="plugin-toolbar">
		<button class="layui-btn layui-btn-primary layui-bg-gray layui-btn-sm" grp-btn lay-event="showAllPlugin">全部</button>
        <button class="layui-btn layui-btn-primary layui-bg-green layui-btn-sm" grp-btn lay-event="showInstalled">已安装</button>
        <button class="layui-btn layui-btn-primary layui-bg-gray layui-btn-sm" grp-btn lay-event="showWaitInstall">待安装</button>
	</script>
    <script type="text/html" id="plugin-state">
        {{# if(d.install == true){ }}
		<input type="checkbox" name="state" value="{{d.platform}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="pluginEnable" {{ d.state == 1 ? 'checked' : '' }} />
        {{# }else{ }}
        <span class="layui-badge layui-bg-gray">未安装</span>
        {{# } }}
	</script>
    <script type="text/html" id="plugin-action">
        {{# if(d.install == true){ }}
        <a href="javascript:;" class="layui-font-green" lay-event="pluginUpdate">更新</a><div class="divider-vl"></div>
        <a href="javascript:;" class="layui-font-green" lay-event="pluginUninstall">卸载</a>
        {{# }else{ }}
        <a href="javascript:;" class="layui-font-green" lay-event="pluginInstall">立即安装</a>
        {{# } }}
	</script>
    <script type="text/html" id="plugin-pay">
        <div class="layui-bg-gray layui-padding-3" style="height: 100%;">
            <div class="layui-card" style="max-width: 320px;min-width: 240px;margin: 0 auto;text-align: center;">
                <div class="layui-card-header">
                    <strong>请使用{{- d.paytype==='alipay'?'<span class="layui-font-blue">支付宝</span>':'<span class="layui-font-green">微信支付</span>' }}付款</strong>
                </div>
                <div class="layui-card-body">
                    <div class="price"><p><span class="layui-font-red layui-font-18">{{= d.money }}</span>元</p><p>商品：{{= d.name }}</p><p>订单：{{= d.orderid }}</p></div>
                    <div class="layui-padding-3 paycode"><img id="qrcode" src="/static/img/loading.gif" width="100%" /></div>
                    <div class="note">
                        <p>支付<span class="layui-font-red">{{= d.money }}</span>元，不要多付或少付</p>
                        <p><span class="layui-font-blue">{{= d.closetime }}</span> 前支付</p>
                        <p>支付完成点击确认支付，过期请不要支付</p>
                    </div>
                </div>
            </div>
        </div>
    </script>
    <script src="/component/layui/layui.js"></script>
    <script src="/component/pear/pear.js"></script>
    <script src="/static/js/awesome-qr.min.js"></script>
    <script>
        const QR = AwesomeQR.AwesomeQR;
        layui.use(['layer', 'form', 'common', 'layer', 'laytpl'], function () {
            let table = layui.table;
            let layer = layui.layer;
            let form = layui.form;
            let common = layui.common;
            let util = layui.util;
            let laytpl = layui.laytpl;

            const cols = [[
                { title: '收款平台名称', field: 'name', align: 'center', maxWidth: 180 },
                { title: '官网', field: 'name', align: 'left', maxWidth: 220, templet: `<div><a href="{{= d.website }}" class="layui-font-green" target="_blank">{{= d.website }}</a></div>` },
                { title: '说明', field: 'describe', align: 'left' },
                { title: '价格', field: 'price', align: 'center', width: 120, templet: `<div>{{= d.price==0 ? '免费' : d.price }}</div>` },
                { title: '状态', field: 'state', align: 'center', width: 120, templet: `#plugin-state` },
                { title: '教程', field: 'helplink', align: 'center', width: 120, templet: `<div><a href="{{= d.helplink }}" class="layui-font-green" target="_blank">使用文档</a></div>` },
                { title: '操作', align: 'center', width: 180, fixed: 'right', templet: `#plugin-action` },
            ]]

            table.render({
                id: 'plugin-table',
                elem: '#plugin-table',
                url: '/api/Plugin/getPluginList',
                skin: 'line',
                cols: cols,
                where: { show: 1 },
                className: 'header-th',
                toolbar: '#plugin-toolbar',
                defaultToolbar: [{ title: '刷新', layEvent: 'refresh', icon: 'layui-icon-refresh' }]
            });
            // 表头工具事件
            table.on('toolbar(plugin-table)', function (obj) {
                if (obj.event === 'showAllPlugin') {
                    table.reloadData('plugin-table', { where: { show: 0 }, done: () => { plugin.changClass(obj.event) } });
                } else if (obj.event === 'showInstalled') {
                    table.reloadData('plugin-table', { where: { show: 1 }, done: () => { plugin.changClass(obj.event) } });
                } else if (obj.event === 'showWaitInstall') {
                    table.reloadData('plugin-table', { where: { show: 2 }, done: () => { plugin.changClass(obj.event) } });
                }
            });
            // 单元格事件
            table.on('tool(plugin-table)', function (obj) {
                const id = obj.data.id;
                if (obj.event === 'pluginInstall') {
                    plugin.install({ platform: obj.data.platform });
                } else if (obj.event === 'pluginUpdate') {
                    plugin.update({ platform: obj.data.platform });
                } else if (obj.event === 'pluginUninstall') {
                    layer.confirm('卸载之后无法恢复，确认吗？', { icon: 3, title: '卸载插件' }, function (index) {
                        layer.close(index);
                        plugin.uninstall({ platform: obj.data.platform });
                    });
                }
            });
            // 启用状态
            form.on('switch(pluginEnable)', function (obj) {
                const state = obj.elem.checked == true ? 1 : 0;
                const platform = obj.value;
                const field = { state: state, platform: platform };
                plugin.enable(obj, field);
                return false;
            });

            let plugin = {};

            // 处理点击btn切换class
            plugin.changClass = (event) => {
                const select = 'layui-btn layui-btn-primary layui-bg-green layui-btn-sm';
                const unselect = 'layui-btn layui-btn-primary layui-bg-gray layui-btn-sm';
                const ele = document.querySelector(`button[lay-event="${event}"]`);
                ele.className = select;
                const btns = document.querySelectorAll(`button[grp-btn]`);
                btns.forEach(val => {
                    if (ele != val) {
                        val.className = unselect;
                    }
                });
            }
            // 启用
            plugin.enable = async (obj, field) => {
                const res = await fetch('/api/Plugin/pluginEnable', { method: 'post', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(field) });
                if (res.status !== 200) {
                    layer.msg('请求失败，请重试！', { tips: 2, time: 1200 }, () => { obj.elem.checked = !obj.elem.checked });
                    return false;
                }
                const rec_info = await res.json();
                if (rec_info.code === 0) {
                    layer.tips(rec_info.msg, obj.othis, { tips: 1, time: 1200 });
                } else {
                    layer.msg(rec_info.msg, { icon: 2, time: 1200 }, () => { obj.elem.checked = !obj.elem.checked });
                }
            }
            // 卸载插件
            plugin.uninstall = async (config) => {
                const load = layer.load(2);
                const res = await fetch('/api/Plugin/uninstallPlugin', { method: 'post', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(config) });
                if (res.status !== 200) {
                    layer.msg('请求失败，请重试！', { tips: 2, time: 1200 });
                    layer.close(load);
                    return false;
                }
                const rec_info = await res.json();
                if (rec_info.code === 0) {
                    layer.msg(rec_info.msg, { icon: 1, time: 1200 }, () => { table.reload('plugin-table'); });
                    layer.close(load);
                    return false;
                } else {
                    layer.msg(rec_info.msg, { icon: 2, time: 1200 });
                    layer.close(load);
                    return false;
                }
            }
            // 安装插件
            plugin.install = async (config, step = 0) => {
                // 加载中
                const load = layer.load(2);
                const res = await fetch('/api/Plugin/installPlugin', { method: 'post', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(config) });
                if (res.status !== 200) {
                    layer.close(load);
                    layer.msg('请求失败，请重试！', { tips: 2, time: 1200 });
                    return false;
                }
                const rec_info = await res.json();
                // 错误信息
                if (rec_info.code !== 0) {
                    layer.close(load);
                    layer.msg(rec_info.msg, { icon: 2, time: 1200 });
                    return false;
                }
                const info = rec_info.data;
                if (rec_info.state === 0) {
                    plugin.pay(info, config.platform, step);
                    layer.close(load);
                    return false;
                } else {
                    // 安装成功
                    layer.close(load);
                    layer.msg(rec_info.msg, { icon: 1, time: 1200 }, () => { table.reload('plugin-table'); });
                    return false;
                }
            }
            // 更新插件
            plugin.update = async (config) => {
                const load = layer.load(2);
                const res = await fetch('/api/Plugin/updatePlugin', { method: 'post', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(config) });
                if (res.status !== 200) {
                    layer.msg('请求失败，请重试！', { tips: 2, time: 1200 });
                    layer.close(load);
                    return false;
                }
                const rec_info = await res.json();
                if (rec_info.code === 0) {
                    layer.close(load);
                    layer.msg(rec_info.msg, { icon: 1, time: 1200 }, () => { table.reload('plugin-table'); });
                    return false;
                } else {
                    layer.close(load);
                    layer.msg(rec_info.msg, { icon: 2, time: 1200 });
                    return false;
                }
            }
            // 支付费用
            plugin.pay = (config, platform, step) => {
                if (step == 0) {
                    plugin.payPage(config, platform);
                } else {
                    layer.alert('支付失败，请重试！', { icon: 0, title: '提示' }, function (index) {
                        layer.close(index);
                        plugin.payPage(config, platform);
                    });
                }
            }
            plugin.payPage = async (config, platform) => {
                layer.open({
                    type: 1,
                    title: '支付费用',
                    area: [common.isModile() ? '100%' : '360px', common.isModile() ? '100%' : 'auto'],
                    content: laytpl(document.getElementById('plugin-pay').innerHTML).render(config),
                    offset: '16px',
                    anim: 1,
                    btn: ['确认支付', '取消'],
                    success: function () {
                        plugin.setQrcode(config.codetype, config.payurl);
                    },
                    yes: (index) => {
                        layer.close(index);
                        layer.load(2);
                        plugin.install({ platform: platform }, 1);
                    },
                    btn2: (index) => {
                        layer.close(index);
                    }
                })
            }
            // 设置二维码
            plugin.setQrcode = async (codeType, payCode) => {
                if (codeType == 0) {
                    document.getElementById('qrcode').src = await getQrcode(payCode);
                } else {
                    document.getElementById('qrcode').src = payCode;
                }
            }
        });
        // 生成二维码
        async function getQrcode(text) {
            const qrcodeUrl = await new Promise((resolve) => {
                new QR({
                    text: text,
                    size: 500,
                }).draw().then((dataURL) => { resolve(dataURL); });
            })
            return qrcodeUrl;
        }
    </script>
</body>

</html>